// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
const $ = db.command.aggregate

// 创建集合云函数入口函数
exports.main = async (event, context) => {
    try {
        let {
            conditions
        } = event.data

        const now = new Date();
        const dayOfWeek = now.getDay(); // 0-6, 0代表周日

        // 计算本周一和本周日的日期
        const monday = new Date(now);
        monday.setDate(now.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1));

        const sunday = new Date(monday);
        sunday.setDate(monday.getDate() + 6);

        let query = db.collection('agentCouponRecord')

        // 查询本周优惠券使用情况
        const couponResult = await query.aggregate().match({
                ...conditions,
                createTime: {
                    $gte: monday.getTime(),
                    $lte: sunday.getTime(),
                }
            })
            .unwind('$couponName')
            .group({
                _id: '$couponName',
                couponNum: $.sum('$couponNum'),
            })
            .end()

        let couponData = []
        if (couponResult.list.length > 0) {
            couponData = couponResult.list.map(item => {
                return {
                    couponName: item._id,
                    couponNum: item.couponNum,
                }
            })
        }

        return {
            code: 200,
            msg: "操作成功",
            data: couponData,
        }
    } catch (err) {
        return {
            code: 500,
            message: err.message
        }
    }
}